package com.ruoyi.manager.service.impl;

import java.time.LocalDate;
import java.util.List;

import com.github.pagehelper.Page;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.manager.domain.TReservation;
import com.ruoyi.manager.mapper.TReservationMapper;
import org.apache.ibatis.transaction.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import com.ruoyi.manager.mapper.MemberMapper;
import com.ruoyi.manager.domain.Member;
import com.ruoyi.manager.service.IMemberService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

/**
 * memberService业务层处理
 *
 * @author ruoyi
 * @date 2025-08-12
 */
@Service
public class MemberServiceImpl implements IMemberService {
    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private TReservationMapper reservationMapper;

    /**
     * 查询member
     *
     * @param memberId member主键
     * @return member
     */
    @Override
    @Cacheable(cacheNames = "memberCache" , key = "#memberId")
    public Member selectMemberById(Long memberId) {
        Member member = memberMapper.selectMemberById(memberId);
        return member;
    }

    /**
     * 查询member列表
     *
     * @param member member
     * @return member
     */

    @Override
    public List<Member> selectMemberList(Member member) {
        List<Member> members = memberMapper.selectMemberList(member);
        for (Member m : members) {
            m.setPassword("");
            m.setSalt("");
        }
        return members;
    }

    /**
     * 新增member
     *
     * @param member member
     * @return 结果
     */
    @Override
    public int insertMember(Member member) {
        member.setCreateTime(DateUtils.getNowDate());

        return memberMapper.insertMember(member);
    }

    /**
     * 修改member
     *
     * @param member member
     * @return 结果
     */
    @Override
    @CacheEvict(cacheNames = "memberCache" , key = "#member.id")
    public int updateMember(Member member) {
        return memberMapper.updateMember(member);
    }

    /**
     * 批量删除member
     *
     * @param ids 需要删除的member主键
     * @return 结果
     */
    @Override
    @CacheEvict(value = "memberCache",allEntries = true)
    public int deleteMemberByIds(Long[] ids) {
        return memberMapper.deleteMemberByIds(ids);
    }

    /**
     * 删除member信息
     *
     * @param id member主键
     * @return 结果
     */
    @Override
    @CacheEvict(value = "memberCache",allEntries = true)
    public int deleteMemberById(Long id) {
        return memberMapper.deleteMemberById(id);
    }

    /**
     * 根据会员名称和手机号查询会员信息
     *
     * @param memberName
     * @param phone
     * @return
     */
    @Override
    public Member selectByNameAndPhone(String memberName, String phone) {
        return memberMapper.selectByNameAndPhone(memberName, phone);
    }

    @Override
    public Member login(String phone, String password) {


        Member member = memberMapper.selectByPhone(phone);
        if (member == null) {
            return null;
        }
        //用户不为空
        String pwd = member.getPassword();
        String salt = member.getSalt();

        String md5 = DigestUtils.md5DigestAsHex((salt + password).getBytes());
        System.out.println("MD5: " + md5);

        if (pwd.equals(md5)) {
            return member;
        }
        return null;
    }

    /**
     * 获取当前用户预约信息
     *
     * @param userId
     * @param type
     * @param createTime
     * @param status
     * @return
     */
    @Override
    public Page<Transaction> getReservations(Integer userId, Integer type, LocalDate createTime, Integer status) {
        return reservationMapper.getReservations(userId, type, createTime, status);
    }


    /**
     * 取消预约
     *
     * @param id
     */
    @Transactional
    @Override
    @CacheEvict(cacheNames = "memberCache" , allEntries = true)
    public void cancelReservation(Long id) {

        //先从预约表中查出数据
        TReservation reservation = reservationMapper.selectTReservationById(id);
        if (reservation == null) {
            throw new RuntimeException("预约不存在");
        }
        Long money = reservation.getActualFee();
        Integer memberId = reservation.getMemberId();
        //从用户表查出用户信息
        Member member = memberMapper.selectMemberById(Long.valueOf(memberId));
        if (member == null) {
            throw new RuntimeException("用户不存在");
        }

        member.setBalance(member.getBalance() + money);

        //修改预约表中的状态
        reservation.setStatus(3);
        reservationMapper.updateTReservation(reservation);


        //将金额退回到用户账户
        memberMapper.updateMember(member);

    }


    /**
     * 充值
     *
     * @param phone
     * @param password
     * @param amount
     */
    @Override
    @CacheEvict(value = "memberCache", allEntries = true )
    public void recharge(String phone, String password, Long amount) {
        //先查用户
        Member member = memberMapper.selectByPhone(phone);
        if (member == null) {
            throw new RuntimeException("用户不存在");
        }

        String md5 = DigestUtils.md5DigestAsHex((member.getSalt() + password).getBytes());

        if (!md5.equals(member.getPassword())) {
            throw new RuntimeException("密码错误");
        }

        member.setBalance(member.getBalance() + amount);

        memberMapper.updateMember(member);
    }


    /**
     * 预约审核
     * @param id
     */
    @Override
    @CacheEvict(cacheNames = "reservationCache" , key = "#id")
    public void verifyReservation(Long id) {
        TReservation reservation = reservationMapper.selectTReservationById(id);
        if (reservation == null) {
            throw new RuntimeException("预约不存在");
        }
        reservation.setStatus(1);
        reservationMapper.updateTReservation(reservation);
    }
}
